package com.wbk.lotterysystemuserservice.service.serviceImpl;

import com.wbk.lotterysystemuserservice.entity.User;
import com.wbk.lotterysystemuserservice.entity.UserExt;
import com.wbk.lotterysystemuserservice.entity.UserExtExample;
import com.wbk.lotterysystemuserservice.mapper.UserExtMapper;
import com.wbk.lotterysystemuserservice.service.UserExtInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserExtInfoServiceImpl implements UserExtInfoService {

    @Autowired
    UserExtMapper userExtMapper;

    @Cacheable(cacheNames = "userExt::byUserNo", key = "#userNo")
    @Override
    public UserExt getUserExt(Long userNo) {
        UserExtExample example = new UserExtExample();
        UserExtExample.Criteria criteria = example.createCriteria();
        criteria.andUserNoEqualTo(userNo);
        List<UserExt> userExts = userExtMapper.selectByExample(example);
        if (userExts.isEmpty()) {
            return null;
        }
        return userExts.get(0);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public UserExt save(User user) {
        UserExt userExt = new UserExt();
        userExt.setUserNo(user.getUserNo());
        userExtMapper.insertSelective(userExt);
        return userExt;
    }

    @CacheEvict(cacheNames = "userExt::byUserNo", key = "#userExt.userNo")
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public int update(UserExt userExt) {
        return userExtMapper.updateByPrimaryKeySelective(userExt);
    }
}
